﻿'use client'

import { useState } from 'react'
import { GitCompare, RotateCcw, Copy } from 'lucide-react'

export default function TextDiffPage() {
  const [text1, setText1] = useState('')
  const [text2, setText2] = useState('')
  const [diffResult, setDiffResult] = useState<any[]>([])
  const [compareMode, setCompareMode] = useState('lines')

  const compareTexts = () => {
    if (!text1 && !text2) {
      setDiffResult([])
      return
    }

    let lines1: string[]
    let lines2: string[]

    if (compareMode === 'lines') {
      lines1 = text1.split('\n')
      lines2 = text2.split('\n')
    } else {
      lines1 = text1.split(' ')
      lines2 = text2.split(' ')
    }

    const result: any[] = []
    const maxLength = Math.max(lines1.length, lines2.length)

    for (let i = 0; i < maxLength; i++) {
      const line1 = lines1[i] || ''
      const line2 = lines2[i] || ''

      if (line1 === line2) {
        if (line1) {
          result.push({ type: 'equal', content: line1, lineNumber: i + 1 })
        }
      } else {
        if (line1 && !line2) {
          result.push({ type: 'removed', content: line1, lineNumber: i + 1 })
        } else if (!line1 && line2) {
          result.push({ type: 'added', content: line2, lineNumber: i + 1 })
        } else {
          result.push({ type: 'removed', content: line1, lineNumber: i + 1 })
          result.push({ type: 'added', content: line2, lineNumber: i + 1 })
        }
      }
    }

    setDiffResult(result)
  }

  const handleText1Change = (value: string) => {
    setText1(value)
    setTimeout(compareTexts, 100)
  }

  const handleText2Change = (value: string) => {
    setText2(value)
    setTimeout(compareTexts, 100)
  }

  const copyDiffResult = () => {
    const diffText = diffResult.map(item => {
      const prefix = item.type === 'added' ? '+ ' : item.type === 'removed' ? '- ' : '  '
      return prefix + item.content
    }).join('\n')
    navigator.clipboard?.writeText(diffText)
  }

  const getLineClass = (type: string) => {
    switch (type) {
      case 'added':
        return 'bg-green-100 border-l-4 border-green-500 text-green-800'
      case 'removed':
        return 'bg-red-100 border-l-4 border-red-500 text-red-800'
      case 'equal':
        return 'bg-gray-50 text-gray-700'
      default:
        return 'bg-white text-gray-700'
    }
  }

  const getLinePrefix = (type: string) => {
    switch (type) {
      case 'added':
        return '+ '
      case 'removed':
        return '- '
      case 'equal':
        return '  '
      default:
        return '  '
    }
  }

  return (
    <div className="container mx-auto px-4 py-8">
      <div className="max-w-6xl mx-auto">
        <div className="mb-8">
          <h1 className="text-3xl font-bold text-gray-900 mb-2">文本差异对比</h1>
          <p className="text-gray-600">比较两个文本的差异，高亮显示不同之处</p>
        </div>

        <div className="mb-6 flex gap-4">
          <button
            onClick={compareTexts}
            className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 flex items-center gap-2"
          >
            <GitCompare className="w-4 h-4" />
            比较文本
          </button>
          <button
            onClick={copyDiffResult}
            className="px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 flex items-center gap-2"
          >
            <Copy className="w-4 h-4" />
            复制差异
          </button>
          <button
            onClick={() => { setText1(''); setText2(''); setDiffResult([]) }}
            className="px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 flex items-center gap-2"
          >
            <RotateCcw className="w-4 h-4" />
            清空
          </button>
        </div>

        <div className="mb-6">
          <label className="block text-sm font-medium text-gray-700 mb-2">比较模式</label>
          <select
            value={compareMode}
            onChange={(e) => {
              setCompareMode(e.target.value)
              setTimeout(compareTexts, 100)
            }}
            className="w-full max-w-xs p-2 border border-gray-300 rounded-md"
          >
            <option value="lines">按行比较</option>
            <option value="words">按单词比较</option>
          </select>
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6">
          <div className="space-y-2">
            <label className="text-sm font-medium text-gray-700">原始文本</label>
            <textarea
              value={text1}
              onChange={(e) => handleText1Change(e.target.value)}
              placeholder="输入原始文本..."
              rows={12}
              className="w-full p-3 border border-gray-300 rounded-lg resize-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
            />
          </div>

          <div className="space-y-2">
            <label className="text-sm font-medium text-gray-700">对比文本</label>
            <textarea
              value={text2}
              onChange={(e) => handleText2Change(e.target.value)}
              placeholder="输入要对比的文本..."
              rows={12}
              className="w-full p-3 border border-gray-300 rounded-lg resize-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
            />
          </div>
        </div>

        <div className="mb-6">
          <label className="block text-sm font-medium text-gray-700 mb-2">差异结果</label>
          <div className="bg-white border border-gray-300 rounded-lg p-4 min-h-[300px] max-h-[500px] overflow-y-auto">
            {diffResult.length > 0 ? (
              <div className="space-y-1">
                {diffResult.map((item, index) => (
                  <div key={index} className={p-2 rounded }>
                    <span className="font-mono text-sm">
                      <span className="text-gray-500 mr-2">{item.lineNumber}:</span>
                      <span className="font-bold mr-1">{getLinePrefix(item.type)}</span>
                      {item.content}
                    </span>
                  </div>
                ))}
              </div>
            ) : (
              <div className="text-center text-gray-500 py-8">
                <GitCompare className="w-12 h-12 mx-auto mb-2 text-gray-300" />
                <p className="text-sm">文本差异将在这里显示</p>
              </div>
            )}
          </div>
        </div>

        <div className="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
          <div className="flex items-center space-x-2 p-3 bg-green-50 rounded-lg">
            <div className="w-4 h-4 bg-green-500 rounded"></div>
            <span className="text-sm text-green-800">新增内容</span>
          </div>
          <div className="flex items-center space-x-2 p-3 bg-red-50 rounded-lg">
            <div className="w-4 h-4 bg-red-500 rounded"></div>
            <span className="text-sm text-red-800">删除内容</span>
          </div>
          <div className="flex items-center space-x-2 p-3 bg-gray-50 rounded-lg">
            <div className="w-4 h-4 bg-gray-400 rounded"></div>
            <span className="text-sm text-gray-700">相同内容</span>
          </div>
        </div>

        <div className="bg-gray-50 p-4 rounded-lg">
          <h4 className="font-medium text-gray-900 mb-2">示例数据</h4>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <button
              onClick={() => {
                handleText1Change('Hello World\nThis is line 2\nThis is line 3')
                handleText2Change('Hello World\nThis is modified line 2\nThis is line 3\nThis is new line 4')
              }}
              className="text-left p-3 bg-white rounded border hover:bg-gray-50"
            >
              <div className="font-medium text-sm">简单文本对比</div>
              <div className="text-xs text-gray-500 mt-1">包含修改和新增行的示例</div>
            </button>
            <button
              onClick={() => {
                handleText1Change('apple banana cherry')
                handleText2Change('apple orange cherry date')
              }}
              className="text-left p-3 bg-white rounded border hover:bg-gray-50"
            >
              <div className="font-medium text-sm">单词对比</div>
              <div className="text-xs text-gray-500 mt-1">单词级别的差异对比</div>
            </button>
          </div>
        </div>

        <div className="mt-6 bg-blue-50 p-4 rounded-lg">
          <h4 className="font-medium text-blue-900 mb-2">使用说明</h4>
          <ul className="text-blue-800 text-sm space-y-1">
            <li>• <strong>按行比较:</strong> 逐行对比文本差异，适合代码和文档</li>
            <li>• <strong>按单词比较:</strong> 逐词对比差异，适合短文本和句子</li>
            <li>• <strong>颜色标识:</strong> 绿色表示新增，红色表示删除，灰色表示相同</li>
            <li>• <strong>行号显示:</strong> 显示对应的行号便于定位</li>
            <li>• <strong>实时对比:</strong> 输入时自动进行差异对比</li>
          </ul>
        </div>
      </div>
    </div>
  )
}
